package com.ruoyi.system.outto.game.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.model.domain.AccountInfo;
import com.ruoyi.system.model.domain.InfoImg;
import com.ruoyi.system.model.domain.SalePartner;
import com.ruoyi.system.model.mapper.InfoImgMapper;
import com.ruoyi.system.model.mapper.SuprAuthMapper;
import com.ruoyi.system.outto.core.LCConstant;
import com.ruoyi.system.outto.core.MapUntils;
import com.ruoyi.system.outto.core.OutUrlConstant;
import com.ruoyi.system.outto.core.RegionalCovert;
import com.ruoyi.system.outto.game.CommonApi;
import com.ruoyi.system.outto.game.LCAPI;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lz
 * @version 1.0
 * @date 2022/6/5 16:19
 */
@Slf4j
@Service
public class LCAPIImpl implements LCAPI {

    @Resource
    private InfoImgMapper infoImgMapper;
    @Resource
    private SuprAuthMapper suprAuthMapper;
    @Resource
    private CommonApi commonApi;
    @Value("${desc.title}")
    private String descTitle;
    private SalePartner salePartner;

    @Override
    public AjaxResult addGame(AccountInfo accountInfo, Long userId,SalePartner salePartner) {
        this.salePartner = salePartner;
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> params = params(accountInfo, userId);
        log.info("老曹添加接口请求参数={}", JSONObject.toJSONString(params));
        String response = HttpUtils.sendPost(OutUrlConstant.LCADD, JSONObject.toJSONString(params), "application/json");
        log.info("老曹添加接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);
        if (!"200".equals(resultJson.getString("code"))) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
        }

        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        result.put("msg", resultJson.getString("data"));
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult editGame(AccountInfo accountInfo, Long userId,SalePartner salePartner) {
        this.salePartner = salePartner;
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> params = params(accountInfo, userId);
        log.info("老曹编辑接口请求参数={}", JSONObject.toJSONString(params));
        String response = HttpUtils.sendPost(OutUrlConstant.LCAEDIT, JSONObject.toJSONString(params), "application/json");
        log.info("老曹编辑接口返回参数={}", response);
        JSONObject resultJson = JSONObject.parseObject(response);

        if (!"200".equals(resultJson.getString("code"))) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
        }


        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        result.put("msg", resultJson.getString("data"));
        return AjaxResult.success(result);
    }


    private Map<String, Object> params(AccountInfo accountInfo, Long userId) {

        String replace = accountInfo.getDes().replace("找回", "")
                .replace("人脸", "")
                .replace("有二次", "可二次")
                .replace("包脸", "")
                ;
        accountInfo.setDes(replace);

        String cfRe =  "[\"上海大区-东部\",\"广东大区-南部\",\"广西大区-南部\",\"湖南大区-南部\",\"湖北大区-南部\",\"浙江大区-东部\",\"江苏大区-东部\",\"福建大区-东部\",\"江西大区-南部\",\"陕西大区-西部\",\"四川大区-西部\",\"重庆大区-西部\",\"安徽大区-东部\",\"云南大区-西部\",\"北方大区-北部\",\"辽宁大区-北部\",\"黑龙江大区-北部\",\"吉林大区-北部\",\"北京大区-北部\",\"山东大区-北部\",\"山西大区-北部\",\"河南大区-北部\",\"河北大区-北部\",\"南方大区-南部\",\"教育网大区-东部\",\"移动专区-东部\",\"北方大区-北部\",\"高清竞技大区\"]";
        JSONArray cfReStr = JSONObject.parseArray(cfRe);


        Map<String, Object> params = new TreeMap<>();
        params.put("game", accountInfo.getType());
        if (Objects.isNull(RegionalCovert.getLCPareJson(accountInfo.getType()))) {
            throw new GlobalException("51接口不支持此游戏：" + accountInfo.getType());
        }
        if (Arrays.asList(LCConstant.CoverGames).contains(accountInfo.getType())) {
            if (!Arrays.asList(LCConstant.EXPERCOVER).contains(accountInfo.getType())) {
                String regional = RegionalCovert.toLC(accountInfo.getRegional());
                if (StringUtils.isEmpty(regional)) {
                    throw new GlobalException("大区转换失败，当前系统大区是" + accountInfo.getRegional());
                }
                params.put("cate_name", regional);
            } else {

                JSONArray objects = JSON.parseArray(LCConstant.lccLOLr);
                for (Object object : objects) {
                    String string = object.toString();
                    if (string.contains(accountInfo.getRegional())){
                        params.put("cate_name", string);
                    }
                }
            }
        } else if ("原神".equals(accountInfo.getType())) {
            params.put("cate_name", "米哈游");
        } else if ("光遇".equals(accountInfo.getType())) {
            if ("安卓网易邮箱".equals(accountInfo.getRegional())){
                params.put("cate_name", "安卓官服");
            }
            if ("苹果网易邮箱".equals(accountInfo.getRegional())){
                params.put("cate_name", "苹果官服");
            }

        } else if ("永劫无间".equals(accountInfo.getType())) {
            if (Objects.equals("Steam",accountInfo.getRegional())){
                params.put("cate_name", "steam");
            }else {
                params.put("cate_name", accountInfo.getRegional());
            }

        } else if ("CF端游".equals(accountInfo.getType())){
            params.put("game", "穿越火线");
            for (Object o : cfReStr) {
                String reStr = o.toString();
                String re = reStr.split("-")[0];
                if (re.length() > 2){
                    String substring = re.substring(0, 2);
                    if (accountInfo.getDes().contains(substring)){
                        params.put("cate_name", reStr);
                        break;
                    }
                }
            }
        }

        /**
         * 查询合作伙伴相关信息
         */
        params.put("platform",  this.salePartner.getOther());

        BigDecimal bigDecimal = commonApi.addPrice(accountInfo.getPrice(),  this.salePartner.getSeleep());
        commonApi.setPrice(bigDecimal,accountInfo.getId(), this.salePartner);
        params.put("price", bigDecimal.stripTrailingZeros().toPlainString());

        InfoImg infoImg = new InfoImg();
        infoImg.setInfoId(accountInfo.getId());
        infoImg.setType(Constants.STR_1);
        List<InfoImg> infoImgs = infoImgMapper.selectInfoImgList(infoImg);

        String imgs = "";
        if (Objects.nonNull(accountInfo.getTitleImg())){
            imgs = accountInfo.getTitleImg() + ",";
        }
        if (!CollectionUtils.isEmpty(infoImgs)) {
            imgs = imgs + infoImgs.stream().map(i -> i.getImgUrl()).collect(Collectors.joining(","));
        } else {
            imgs =  imgs + LCConstant.defaultImg;
        }
        params.put("imgs", imgs);
        String title = accountInfo.getDes();
        if (accountInfo.getDes().length() > 150) {
            title = accountInfo.getDes().substring(0, 150);
        }
        title = title.replace(LCConstant.bakFace, "包认证");
        if (Objects.equals(LCConstant.bakFace, accountInfo.getLevel())) {
            params.put("title", "包认证  " + title);
        } else {
            params.put("title",  accountInfo.getLevel() + "  " + title);
        }
        params.put("description", accountInfo.getDes());


        String level = accountInfo.getLevel();
        if (Objects.equals(LCConstant.haveTwo, level)) {
            params.put("is_indulge", 2);
        } else if (Objects.equals(LCConstant.bakFace, level)) {
            params.put("is_indulge", 3);
        } else if (Objects.equals(LCConstant.noMial, level)) {
            params.put("is_indulge", 2);
        } else if (Objects.equals(LCConstant.rezhengMial, level)) {
            params.put("is_indulge", 1);
        } else {
            params.put("is_indulge", 1);
        }
        params.put("p_number", descTitle + accountInfo.getId());
        if (Objects.isNull(accountInfo.getExtractAccount())) {
            throw new GlobalException("请完善账号后再推送");
        }
        params.put("account_number", descTitle + "||" + accountInfo.getId());


        //游戏类型参数
        if (Objects.equals("王者荣耀", accountInfo.getType())) {
            if (Objects.isNull(accountInfo.getHeroes())) {
                params.put("hero_num", 0);
            } else {
                params.put("hero_num", accountInfo.getHeroes());
            }
            if (Objects.isNull(accountInfo.getSkins())) {
                params.put("skin_num", 0);
            } else {
                params.put("skin_num", accountInfo.getSkins());
            }
        } else if (Objects.equals("和平精英", accountInfo.getType())) {

            if (Objects.isNull(accountInfo.getGuns())) {
                params.put("arms_num", 0);
            } else {
                params.put("arms_num", accountInfo.getGuns());
            }
            if (Objects.isNull(accountInfo.getSuit())) {
                params.put("skin_num", 0);
            } else {
                params.put("skin_num", accountInfo.getSuit());
            }
        } else if (Objects.equals("英雄联盟", accountInfo.getType())) {
            if (Objects.isNull(accountInfo.getHeroes())) {
                params.put("hero_num", 0);
            } else {
                params.put("hero_num", accountInfo.getHeroes());
            }
            if (Objects.isNull(accountInfo.getSkins())) {
                params.put("skin_num", 0);
            } else {
                params.put("skin_num", accountInfo.getSkins());
            }
        } else {
            if (Objects.isNull(accountInfo.getHeroes())) {
                params.put("hero_num", 0);
            } else {
                params.put("hero_num", accountInfo.getHeroes());
            }
            if (Objects.isNull(accountInfo.getSkins())) {
                params.put("skin_num", 0);
            } else {
                params.put("skin_num", accountInfo.getSkins());
            }
        }


        String cover = MapUntils.getCover(params);
        cover = cover + "key=" +  this.salePartner.getSaleKey();
        String sign = DigestUtils.md5Hex(cover).toUpperCase();
        log.info("sign={}", sign);
        params.put("sign", sign);
        return params;
    }


    @Override
    public AjaxResult delGame(Long id, Long userId,SalePartner sa) {
        Map<String, Object> params = new TreeMap<>();
        params.put("p_number", descTitle + id);


        params.put("platform", sa.getOther());

        //sign
        String cover = MapUntils.getCover(params);
        cover = cover + "key=" + sa.getSaleKey();
        String sign = DigestUtils.md5Hex(cover).toUpperCase();
        params.put("sign", sign);
        log.info("老曹删除接口请求参数={}", JSONObject.toJSONString(params));
        String response = HttpUtils.sendPost(OutUrlConstant.LCADEL, JSONObject.toJSONString(params), "application/json");
        if (StringUtils.isEmpty(response)) {
            throw new GlobalException("请求接口失败");
        }
        log.info("老曹删除接口返回参数={}", JSONObject.toJSONString(response));
        JSONObject resultJson = JSONObject.parseObject(response);
        Map<String, Object> result = new HashMap<>();

        if (!"200".equals(resultJson.getString("code"))) {
            result.put("code", 500);
        } else {
            result.put("code", 200);
        }

        result.put("req", JSONObject.toJSONString(params));
        result.put("res", response);
        result.put("msg", resultJson.getString("data"));
        return AjaxResult.success(result);
    }



    private String getRea(){
        Map<String, Object> params = new TreeMap<>();
        params.put("platform","xtdanbao");

        String cover = MapUntils.getCover(params);
        cover = cover + "key=wvvbt1rjwvms7o7e319jm7p28jhbqdc3";
        String sign = DigestUtils.md5Hex(cover).toUpperCase();
        params.put("sign", sign);
//        String response = HttpUtils.sendPost(OutUrlConstant.LCADD, JSONObject.toJSONString(params),"application/json");
        String response = HttpUtils.sendPost("https://www.51youxihao.com/index.php?g=api&m=product&a=list_games", JSONObject.toJSONString(params), "application/json");
        System.out.println(response);
        return response;
    }

    public static void main(String[] args) {

        String aa = "王者荣耀";
        String substring = aa.substring(0, 2);
        System.out.println(substring);
//
//        {
//            "game": "王者荣耀",
//                "price": "1800",
//                "cate_name": "安卓QQ",
//                "p_number": "252309",
//                "imgs":"https://youxihao.oss-cn-zhangjiakou.aliyuncs.com/5f7e912c7f7a7.jpg,https://youxihao.oss-cn-zhangjiakou.aliyuncs.com/5f7e912cb88a8.jpg,https://youxihao.oss-cn-zhangjiakou.aliyuncs.com/5f7e912cec9fc.jpg",
//                "description": "4S 11A 三星长门 三星秽土猿飞日斩 三星金角银角 三星鬼灯幻月 67个秽土波风水门碎片 52个猿飞日斩碎片",
//                "platform": "51youxihao",
//                "title": "WT【安卓抠】50英雄31皮肤安卓Q-50英雄31皮肤-夺萃鹰眼祸源150级，至尊宝，忍炎影，龙腾万里，死亡",
//                "is_indulge": 1,
//                "sign": "DBA10184D15A13385E29BE5DCD461ABC",
//        }
//

//        String str = "gm28-安卓q-V7-108英雄-185皮肤-300五级铭文 7王者印记 未来机甲 幽冥火 253幸运值 " +
//                "1内测 蔷薇恋人 零号赤焰 天狼绘梦者 天狼运算者 天狼溯光者 祈雪灵祝 逐梦之星 朱雀志 异界灵契 拒霜思 " +
//                "孙行者 猪悟能 梁祝 地狱火 久胜战神 云霓雀翎 末日机甲女 无限星赏官 原初追逐者 黎明之约 原初探秘者 李小龙 " +
//                "暗隐猎兽者 金属风暴 热力回旋 特工魅影 逐浪之夏 修罗 白龙吟 千年之狐 街头霸王 箭羽风息 星空之诺 鬼剑武藏 " +
//                "朔望之晖 德古拉伯爵 银河之约 暗影游猎 云间偶戏 死神来了 冰冠公主 狂想玩偶喵 单词大作战 花好人间 狰 饕餮 " +
//                "烛龙 重明 穷奇 御霄 御旌 御銮 朔风刀 混沌棋 疑决卦 醍醐杖 万华元夜 女仆咖啡 科学大爆炸 重装意志 奇遇舞章 " +
//                "永昼 营地ID:459926613";
//        String substring = str.substring(0, 150);
//        System.out.println(substring);


        Map<String, Object> params = new TreeMap<>();
//        params.put("game", "王者荣耀");
//        params.put("price", new BigDecimal(1800));
//        params.put("cate_name", "安卓QQ");
//        params.put("p_number", 14356);
//        params.put("imgs", "https://asdasda");
//        params.put("description", "1fasdfadsfasd1");
//        params.put("platform", "yud");
//        params.put("title", "222fdsafasd");

        params.put("platform","xtdanbao");
//        params.put("key","wvvbt1rjwvms7o7e319jm7p28jhbqdc3");

        String cover = MapUntils.getCover(params);
        cover = cover + "key=wvvbt1rjwvms7o7e319jm7p28jhbqdc3";
        String sign = DigestUtils.md5Hex(cover).toUpperCase();
        params.put("sign", sign);
//        String response = HttpUtils.sendPost(OutUrlConstant.LCADD, JSONObject.toJSONString(params),"application/json");
        String response = HttpUtils.sendPost("https://www.51youxihao.com/index.php?g=api&m=product&a=list_games", JSONObject.toJSONString(params), "application/json");
        System.out.println(response);
    }

}
